<template>
  <div class="hzs-userinfo">
    <!-- 个人信息 -->
    <el-row class="main-top">
      <div class="avatar">
        <el-tooltip content="点击上传头像" effect="light">
          <el-upload
            accept="image/*"
            action=""
            :show-file-list="false"
            :http-request="uploadMainImg"
          >
            <el-avatar :size="120" :src="this.userInfo.imageUrl">{{ userInfo.nickName }}</el-avatar>
          </el-upload>
        </el-tooltip>
      </div>

      <div class="info">
        <div>
          <span class="meta-block">&nbsp;&nbsp;&nbsp;昵称：</span>
          <span class="name">{{ userInfo.nickName }}</span>
        </div>
        <div>
          <span class="meta-block">用户名：</span>
          <span class="name">{{ userInfo.username }}</span>
        </div>
      </div>
    </el-row>

    <!--文章类别-->
    <el-row>
      <el-tabs value="public" @tab-click="handleClick">
        <el-tab-pane label="公开文章" name="public">
          <article-list
            name="public"
            :page="query"
            :listData="articleList"
            @fetch-data="this.findUserArticleList"/>
        </el-tab-pane>

        <el-tab-pane label="私密文章" name="no-public">
          <article-list name="no-public"
                        :page="query"
                        :listData="articleList"
                        @fetch-data="this.findUserArticleList"/>
        </el-tab-pane>

        <el-tab-pane label="我的提问" name="question">
          <question-list name="question" :page="query"
                         :listData="questionList" @fetch-data="findUserQuestionList"/>
        </el-tab-pane>


        <el-tab-pane label="修改个人资料" name="user">
          <user-edit :loading="loading" :formData="userInfo" @submitForm="submitUserForm"/>
        </el-tab-pane>
        <el-tab-pane label="修改密码" name="password">
          <user-password :loading="loading" :formData="passwordData" @submitForm="submitPasswordForm"/>
        </el-tab-pane>
      </el-tabs>
    </el-row>
  </div>
</template>
<script>
import ArticleList from '@/components/article/List'
import QuestionList from '@/components/question/List'
import UserEdit from '@/components/user/Edit'
import UserPassword from '@/components/user/Password'

export default {
  // 引用权限中间件
  middleware: 'auth',

  // 组件
  components: {QuestionList, ArticleList, UserEdit, UserPassword},

  data() {
    return {
      // 锁
      loading: false,

      // 用户信息
      userInfo: {
        imageUrl: ''
      },

      // 用户提问列表
      questionList: [],

      // 用户文章列表
      articleList: [],

      // 修改密码表单
      passwordData: {
        userId: this.$store.state.userInfo.uid
      },

    }
  },

  methods: {
    // 处理切换tab的情况
    handleClick(tab, event) {
      switch (tab.paneName) {
        case 'public':
          this.findUserArticleList(tab.paneName, 1)
          break;
        case 'no-public':
          this.findUserArticleList(tab.paneName, 1)
          break;
        case 'question': // ++++++
          this.findUserQuestionList(tab.paneName, 1)
          break;
        case 'user':
          // 用户不用查询，在加载此页面时已经查询了
          break;
      }
    },

    // 上传头像
    async uploadMainImg(file) {
      // 封装表单对象
      const fileData = new FormData()
      fileData.append('file', file.file)

      // 加锁
      this.loading = true

      try {
        // 发送请求上传
        console.log("即将更新的表单")
        console.log(file.file)
        const {data} = await this.$uploadImg(fileData)
        // 把原来的图片删除
        this.deleteImg()

        // 删除后赋新值
        this.userInfo.imageUrl = data

        // 更新用户数据（imageUrl）
        // this.$updateUserInfo(this.userInfo)
        const {code, message} = await this.$updateUserInfo(this.userInfo)
        if (code === 20000) {
          this.$message.success('修改成功')
          this.$cookies.set("userInfo", this.userInfo)

        } else {
          this.$message.error(message)
        }
        // 放锁
        this.loading = false

      } catch (error) {
        this.$message.error('上传失败')

        // 放锁
        this.loading = false
      }
    },
    // 删除头像, 上传成功后删除原来的头像
    deleteImg() {
      if (this.userInfo.imageUrl) {
        // 删除
        this.$deleteImg(this.userInfo.imageUrl)
      }
    },

    // 提交修改个人资料
    async submitUserForm() {
      // 加锁
      this.loading = true
      // console.log('userInfo', this.userInfo)
      const {code, message} = await this.$updateUserInfo(this.userInfo)
      if (code === 20000) {
        this.$message.success('修改成功')
      } else {
        this.$message.error(message)
      }

      // 放锁
      this.loading = false
    },


    // 修改密码
    async submitPasswordForm() {
      // 加锁
      this.loading = true

      // 提交修改
      this.passwordData.userId = this.$store.state.userInfo && this.$store.state.userInfo.uid
      const res = await this.$updatePassword(this.passwordData)

      // 如果res状态码正确
      if (res.code === 20000) {
        // 清空
        this.passwordData = {}

        // 跳转登录页
        this.$store.dispatch('UserLogout')
      } else {
        this.$message.error(res.message)
      }

      this.loading = false
    },

    // 查询文章列表(标签名，当前页码)
    async findUserArticleList(paneName, current) {
      // 设置查询条件
      this.query.current = current

      // 0未公开，1公开
      this.query.isPublic = paneName === 'public' ? 1 : 0

      // 查询，不要少了 $
      const {data} = await this.$findUserArticle(this.query)

      // 总记录数
      this.query.total = data.total

      // 列表数据
      this.articleList = data['records']
    },

    // 查询我的提问列表(标签名，当前页码)
    async findUserQuestionList(paneName, current) {
      // 设置查询条件
      this.query.current = current

      // 用户提问列表不需要isPublic，删除它
      delete this.query.isPublic
      console.log('query', this.query)
      // 查询，不要少了 $
      const {data} = await this.$findUserQuestion(this.query)
      // 总记录数
      this.query.total = data.total
      // 提问列表数据
      this.questionList = data.records
    },

  },

  // 服务端异步获取数据
  async asyncData({app, store}) {
    const userId = store.state.userInfo && store.state.userInfo.uid
    // 1. 查询用户信息
    const {data: userInfo} = await app.$getUserInfo(userId)
    // console.log('userInfo', userInfo)
    // 2. 查询公开文章列表
    // 封装查询条件
    const query = {
      userId,
      isPublic: 1, // 0未公开，1公开
      current: 1,
      size: 20,
      total: 0
    }

    // 请求数据
    const {data} = await app.$findUserArticle(query)
    query.total = data.total
    return {
      userInfo,
      query,
      articleList: data['records']
    }
  },

}
</script>
<style>
.hzs-userinfo {
  padding: 30px;
  border-radius: 30px;
  background-color: #FFFFFF;
  border: 2px solid black;
  margin-bottom: 100px;
}

.hzs-userinfo .main-top {
  padding: 30px 0;
  /*background-color: #FFFFFF;*/
}

.hzs-userinfo .avatar {
  float: left;
}

.hzs-userinfo .info {
  margin: 30px 0 0 140px;
}

.hzs-userinfo .info .name {
  font-size: 18px;
  font-weight: 500;
  padding-top: 10px;
}

.hzs-userinfo .info .meta-block {
  font-size: 14px;
  color: #969696;
}
</style>
